package com.onlyxiahui.framework.action.dispatcher.general.config;

import com.onlyxiahui.framework.action.dispatcher.ActionContext;
import com.onlyxiahui.framework.action.dispatcher.ActionDispatcher;
import com.onlyxiahui.framework.action.dispatcher.config.ActionConfigurer;
import com.onlyxiahui.framework.action.dispatcher.extend.ActionBox;
import com.onlyxiahui.framework.action.dispatcher.general.impl.GeneralActionValidInterceptor;
import com.onlyxiahui.framework.json.validator.ValidatorService;

/**
 * Date 2019-04-20 08:13:26<br>
 * Description
 * 
 * @author XiaHui<br>
 * @since 1.0.0
 */
public class GeneralActionDispatcher extends ActionDispatcher {

	private final ValidatorService validatorService = new ValidatorService();
	private GeneralActionDefaultConfigurer handlerActionConfigurer = new GeneralActionDefaultConfigurer();
	private GeneralActionValidInterceptor handlerActionInterceptor = new GeneralActionValidInterceptor();

	public GeneralActionDispatcher() {
		this.initialize();
	}

	public GeneralActionDispatcher(ActionBox actionBox) {
		this.initialize();
		this.add(actionBox);
	}

	public GeneralActionDispatcher(ActionBox actionBox, String... actionLocations) {
		this.initialize();
		this.add(actionBox);
		this.scan(actionLocations);
	}

	public void addActionValidator(String actionValidatorConfigPath) {
		// "classpath*:/validator/main/action/*.json"
		validatorService.loadValidatorConfig(actionValidatorConfigPath);
	}

	public void setActionValidateRootProperty(String validateProperty) {
		handlerActionInterceptor.setValidateRootProperty(validateProperty);
	}

	public ValidatorService getValidatorService() {
		return validatorService;
	}

	@Override
	public void addConfig(ActionConfigurer actionConfigurer) {
		super.addConfig(actionConfigurer);
	}

	private void initialize() {
		handlerActionInterceptor.setValidatorService(validatorService);
		this.addConfig(handlerActionConfigurer);
		this.addConfig(new GeneralActionConfigurerAdapter() {
			@Override
			public void addConfig(ActionContext actionContext) {
				actionContext.getActionInterceptorRegistry().add(handlerActionInterceptor);
			}
		});
	}

	public void add(ActionBox actionBox) {
		// "com.*.action"
		this.addConfig(new GeneralActionConfigurerAdapter() {
			@Override
			public void addConfig(ActionContext actionContext) {
				actionContext.getActionBoxRegistry().add(actionBox);
			}
		});
	}
}
